package com.rabbitmq.demo.conf;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RPC模式
 *
 * @Author yi.cheng
 * @Date 2023-7-17 09:49
 **/
@Configuration
public class RPCQueueConfig {

    public final static String RPC_QUEUE_ONE = "rpc_queue";

    @Bean
    public Queue rpcQueue() {
        return new Queue(RPC_QUEUE_ONE, true);
    }

    @Bean
    DirectExchange topicExchange(){
        return new DirectExchange("direct");
    }

    @Bean
    public Binding bindingExchangeQueue(){
        return BindingBuilder.bind(rpcQueue()).to(topicExchange()).with("direct");
    }

    @Bean
    public RabbitTemplate directRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter());

        //这一步非常关键
        template.setUseTemporaryReplyQueues(false);
        template.setReplyAddress("amq.rabbitmq.reply-to");
        // template.expectedQueueNames();
        template.setUserCorrelationId(true);

        //设置请求超时时间为10s
        template.setReplyTimeout(10000);
        return template;
    }

}
